import os
import time
from dashscope.audio.asr import Transcription
import requests
# 配置您的API Key环境变量，请勿硬编码
# os.environ["DASHSCOPE_API_KEY"] = "sk-4adf3d4278414c21abf8f26fa9aaa267" 

def get_text_from_url(url):
    try:
        response = requests.get(url)
        response.raise_for_status()  # 检查请求是否成功
        data = response.json()
        if 'transcripts' in data and isinstance(data['transcripts'], list) and data['transcripts']:
            return data['transcripts'][0].get('text', '')
    except requests.RequestException as e:
        print(f"请求失败: {e}")
        return None

def asr_transcribe_async():
    """
    异步提交音频转写任务并轮询获取结果
    """
    try:
        # 1. 异步提交任务
        print("正在提交音频转写任务...")
        task = Transcription.async_call(
            model='paraformer-v2',
            file_urls=[audio_url],
            timestamp_alignment_enabled=True
        )
        
        # 2. 检查任务提交状态
        if task.status_code == 200:
            task_id = task.output.task_id
            print(f"任务提交成功，任务ID为: {task_id}")
            print("正在等待任务完成...")
            
            # 3. 异步查询任务结果（轮询）
            while True:
                # 每隔5秒查询一次任务状态
                time.sleep(5)
                fetch_result = Transcription.fetch(task_id)
                
                # 检查任务的顶层状态
                if fetch_result.output.task_status == 'SUCCEEDED':
                    print("任务成功完成！")
                    # 4. 遍历并处理每个子任务的识别结果
                    results = fetch_result.output.results
                    for res in results:
                        # 从字典中获取子任务状态
                        subtask_status = res.get('subtask_status')
                        if subtask_status == 'SUCCEEDED':
                            print(f"文件URL: {res.get('file_url')}")
                            # 获取识别结果的URL
                            print(f"识别结果URL: {res.get('transcription_url')}")
                            print("----------------------------------------")
                            transcription_text = get_text_from_url(res.get('transcription_url'))
                            if transcription_text:
                                print("\n--- 识别结果全文 ---")
                                print(transcription_text)
                                print("\n" + "-"*40)
                            else:
                                print("未能获取识别结果文本。")
                            
                        elif subtask_status == 'FAILED':
                            # 处理失败的子任务
                            print(f"子任务失败，文件URL: {res.get('file_url')}")
                            print(f"错误码: {res.get('code')}")
                            print(f"错误信息: {res.get('message')}")
                            
                    break  # 退出循环
                
                elif fetch_result.output.task_status == 'FAILED':
                    # 处理整个任务失败的情况
                    print("任务失败！")
                    print(f"错误码: {fetch_result.output.code}")
                    print(f"错误信息: {fetch_result.output.message}")
                    break  # 退出循环
                else:
                    print(f"任务状态: {fetch_result.output.task_status}，继续等待...")

        else:
            print(f"任务提交失败，HTTP状态码: {task.status_code}")
            print(f"错误信息: {task.message}")

    except Exception as e:
        print(f"发生错误: {e}")

if __name__ == '__main__':
    audio_url = input("请输入音频文件的URL地址: ").strip()
    asr_transcribe_async()